<!DOCTYPE html>
<html lang="en">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<meta
			name="viewport"
			content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0,user-scalable=no"
		/>
		<meta name="format-detection" content="telephone=yes" />
		<meta name="format-detection" content="email=no" />
		<meta http-equiv="Pragma" content="no-cache" />
		<meta http-equiv="Cache-Control" content="no-cache" />
		<meta http-equiv="Expires" content="0" />
		<title>确认订单</title>
		<!-- 引入 vant UI 组件库样式文件 -->
		<link rel="stylesheet" href="../common/css/vant-index.css" />
		<link rel="stylesheet" href="../common/css/common.css" />
		<link rel="stylesheet" href="./css/confirm.css" />
		<!-- <link rel="stylesheet" href="./css/index.css" /> -->
		<style type="text/css">
			#app {
				height: 100%;
			}
		</style>
	</head>

	<body>
		<div id="app" v-cloak>
			<div class="container">
				<div class="tab" v-if="type">
					<div
						:class="active==1?'tab_pane active':'tab_pane'"
						@click="handleClick(1)"
					>
						线下领取
					</div>
					<div>
						<div
							v-else
							:class="active==2?'tab_pane active':'tab_pane'"
							@click="handleClick(2)"
						>
							配送到家
						</div>
					</div>
				</div>
			</div>
			<div class="address" v-if="active==2">
				<template v-if="address.length == 0">
					<van-cell title="请填写收货地址" is-link @click="addAddress">
						<template #icon>
							<img
								src="./img/add.png"
								style="
									width: 0.48rem;
									height: 0.48rem;
									border-radius: 50%;
									margin-right: 0.16rem;
								"
							/>
						</template>
					</van-cell>
					<van-cell title="一键使用微信收货地址" is-link @click="addWxAddress">
						<template #icon>
							<img
								src="./img/wechat.png"
								style="
									width: 0.48rem;
									height: 0.48rem;
									border-radius: 50%;
									margin-right: 0.16rem;
								"
							/>
						</template>
					</van-cell>
				</template>
				<template v-else>
					<div class="address_card" @click="addAddress(area)">
						<div class="card_left">
							<img src="./img/address.png" />
						</div>
						<div class="card_right">
							<p>
								<span
									style="
										font-size: 0.33rem;
										color: #333333;
										margin-right: 0.24rem;
									"
									>{{area.contact_person}}</span
								>
								<span style="font-size: 0.25rem; color: #666666"
									>{{area.contact_phone}}</span
								>
							</p>
							<p style="width: 4.78rem; margin-top: 0.16rem; color: #333333">
								{{area.contact_full_address}}
							</p>
							<p
								style="color: #666666; font-size: 0.25rem; margin-top: 0.26rem"
							>
								配送方式：
							</p>
						</div>
						<p
							style="
								position: absolute;
								right: 0.24rem;
								bottom: 0.24rem;
								color: #333333;
								font-size: 0.29rem;
							"
						>
							<span style="margin-right: 0.3rem">快递</span><span>免费</span>
						</p>
						<img
							src="./img/arrow.png"
							style="
								position: absolute;
								right: 0.24rem;
								top: 0.96rem;
								width: 0.32rem;
								height: 0.32rem;
							"
						/>
					</div>
				</template>
			</div>
			<div class="good_card" v-for="item in products">
				<img :src="item.product_banner[0]" class="good_img" />
				<div style="display: flex; flex-direction: column; width: 4.16rem">
					<div>
						<p
							style="font-size: 0.33rem; color: #333333; margin-bottom: 0.16rem"
						>
							{{item.product_name}}
						</p>
						<!-- <div class="serve_time" v-else>{{item.service_period}}</div> -->
					</div>
					<div class="good">
						<p class="good_price">
							￥{{item[this.usePrice]}}
							<!-- ￥{{usePrice ==
							'productFormatDiscountPrice'?item.product_discount_price:usePrice
							==
							'productFormatVipPrice'?item.product_vip_price:item.product_price}} -->
						</p>
						<span style="font-size: 0.28rem; color: #999999"
							>X{{item.num}}</span
						>
					</div>
				</div>
			</div>
			<div class="agree" v-if="some" @click="handleAgree">
				<img :src="agree?'./img/select.png':'./img/unselect.png'" />
				<span>我已阅读并同意<a @click.stop="click">《知情同意书》</a></span>
			</div>
			<div class="bottom">
				<div style="margin-top: 0.24rem; margin-left: 0.54rem">共{{sum}}件</div>
				<div style="margin-left: 0.24rem; width: 3.54rem">
					<div style="margin-top: 0.08rem">
						<span>合计：</span
						><span style="font-size: 0.4rem; color: #e22e30">￥{{total}}</span>
					</div>
					<!-- <div style="margin-top: 0.08rem">
						<span>共减：</span
						><span
							>￥{{((detail.product_price-detail.product_discount_price)*detail.num).toFixed(2)}}</span
						>
					</div> -->
				</div>
				<van-button v-if="is_pay" class="btn" @click="onSubmit"
					>提交订单</van-button
				>
				<van-button v-else class="btn" @click="onPay">立即支付</van-button>
			</div>
		</div>
	</body>
	<!-- 引入 rem -->
	<script src="../common/js/rem.js"></script>
	<script src="./js/adjust.js"></script>
	<!-- 上线环境用 -->
	<script src="../common/js/vue.global.prod.js?time=202209061605"></script>
	<!-- 引入 UI 组件库 -->
	<script src="../common/js/vant.min.js"></script>
	<!-- axios 接口调用 -->
	<script src="../common/js/axios.min.js"></script>
	<script src="../base.js"></script>
	<script src="../common/js/url.min.js"></script>
	<script src="../common/js/swiper.min.js"></script>
	<script src="https://res2.wx.qq.com/open/js/jweixin-1.6.0.js "></script>
	<!-- <script src="https://cdn.bootcdn.net/ajax/libs/vConsole/3.9.0/vconsole.min.js"></script> -->

	<script type="module">
		// var vConsole = new VConsole()
		import {
			getAction,
			postAction,
			spliceUrl,
			getNow,
		} from '../common/js/api/vue3-axios-utils.js'

		const PatientData = {
			data() {
				return {
					active: 0,
					agree: false,
					detail: {},
					products: [],
					usePrice: 'product_price',
					pid: '',
					is_pay: true,
					address: [],
					list: [],
					order_id: '',
				}
			},
			computed: {
				type() {
					const type = this.products.every(v => {
						return v.product_category == 3
					})
					console.log(type, 'type')
					return !type
				},
				some() {
					const some = this.products.some(v => {
						return v.product_category == 3
					})
					console.log(some, 'some')
					return some
				},
				sum() {
					const num = this.products.map(v => {
						return Number(v.num)
					})
					const sum =
						num.length > 0 &&
						num.reduce((v, i) => {
							return v + i
						})
					return sum || 0
				},
				total() {
					let price = []
					this.products.forEach(v => {
						// if (this.usePrice == 'productFormatDiscountPrice') {
						// 	price.push(Number(v.num) * Number(v.product_discount_price))
						// } else if (this.usePrice == 'productFormatVipPrice') {
						// 	price.push(Number(v.num) * Number(v.product_vip_price))
						// } else {
						// 	price.push(Number(v.num) * Number(v.product_price))
						// }
						price.push(Number(v.num) * Number(v[this.usePrice]))
					})
					const total =
						price.length > 0 &&
						price.reduce((v, i) => {
							return v + i
						})
					return total || 0
				},
			},
			created() {
				this.pid = url('?pid')
				this.active = url('?active') || 0
				this.onweixin()
				this.getLocation()
				this.getList()
			},
			mounted() {},
			methods: {
				onweixin() {
					postAction(spliceUrl('/shop/order/jssdk'), {
						// url: 'http://h5.test.dtx-tech.com/mall/mallIndex.html?parent_id=667',
						url: location.href.split('#')[0],
					}).then(res => {
						res = res.data
						if (res.success) {
							wx.config({
								debug: false, // 调试时可开启
								appId: res.data.appId, // <!-- replace -->
								timestamp: res.data.timestamp, // 必填，填任意数字即可
								nonceStr: res.data.nonceStr, // 必填，填任意非空字符串即可
								signature: res.data.signature, // 必填，填任意非空字符串即可
								jsApiList: [...res.data.jsApiList, 'openAddress'], // 必填，随意一个接口即可
								openTagList: res.data.openTagList, // 填入打开小程序的开放标签名
							})
						} else {
							this.$toast.fail({
								message: res.message,
							})
						}
					})
				},
				addWxAddress() {
					wx.openAddress({
						success: res => {
							console.log(res)
							const area = {
								patient_id: this.pid,
								contact_person: res.userName,
								contact_phone: res.telNumber,
								contact_province_id: res.nationalCode.substr(0, 2) + '0000',
								contact_province_name: res.provinceName,
								contact_city_id: res.nationalCode.substr(0, 4) + '00',
								contact_city_name: res.cityName,
								contact_district_id: res.nationalCode,
								contact_district_name: res.countryName,
								contact_address: res.detailInfo,
								is_default: 1,
							}
							postAction(spliceUrl('/shop/address/save'), area).then(r => {
								r = r.data
								if (r.success) {
									this.$toast.success({
										message: '保存成功',
									})
									this.getLocation()
								} else {
									this.$toast.fail({
										message: res.message,
									})
								}
							})
						},
					})
				},
				getLocation() {
					getAction(spliceUrl('/shop/address'), { patient_id: this.pid }).then(
						res => {
							res = res.data
							if (res.success) {
								this.address = res.data
								this.area = this.address[0]
							} else {
								this.$toast.fail({
									message: res.message,
								})
							}
						}
					)
				},
				getList() {
					const products = JSON.parse(sessionStorage.getItem('products'))
					const priceField = [
						'product_price',
						'product_discount_price',
						'product_vip_price',
					]
					if (
						priceField.indexOf(
							JSON.parse(sessionStorage.getItem('usePrice'))
						) != -1
					) {
						this.usePrice = JSON.parse(sessionStorage.getItem('usePrice'))
					}
					postAction(spliceUrl('/shop/order/confirm'), {
						patient_id: this.pid,
						products: products,
						use_price: this.usePrice,
					}).then(res => {
						res = res.data
						if (res.success) {
							this.products = res.data.list
						}
					})
				},
				handleClick(item) {
					if (item == this.active) {
						this.active = 0
					} else {
						this.active = item
					}
				},
				click() {
					window.location.href = './consent.html'
				},
				toService() {
					window.location.href = './service.html'
				},
				check() {
					if (this.type) {
						if (!this.active) {
							this.$toast.fail({
								message: '请选择领件方式!',
							})
							return false
						}
						if (this.active == 2 && this.address.length == 0) {
							this.$toast.fail({
								message: '请填写收货地址!',
							})
							return false
						}
					}
					if (this.some) {
						if (!this.agree) {
							this.$toast.fail({
								message: '请阅读《知情同意书》及《服务协议》并勾选',
							})
							return false
						}
					}
					return true
				},
				addAddress(item) {
					sessionStorage.setItem('area', JSON.stringify(item))
					window.location.href =
						'./address.html?pid=' + this.pid + '&active=' + this.active
				},
				handleAgree() {
					this.agree = this.agree ? false : true
				},
				onSubmit() {
					if (!this.check()) return
					const params = {
						patient_id: this.pid,
						products: this.products.map(v => {
							return {
								id: v.data_id,
								num: v.num,
							}
						}),
						use_price: this.usePrice,
						delivery_type: this.active,
						remark: '',
					}
					this.active == 2 && (params.address_id = this.address[0].data_id)
					postAction(spliceUrl('/shop/order/create'), params).then(res => {
						res = res.data
						if (res.success) {
							this.order_id = res.data.order_id
							postAction(spliceUrl('/shop/order/pay'), {
								order_id: res.data.order_id,
								patient_id: this.pid,
							}).then(result => {
								result = result.data
								if (result.success) {
									this.wxPay(result.data)
								}
							})
						} else {
							this.$toast.fail({
								message: res.message,
							})
						}
					})
				},
				wxPay(item) {
					wx.chooseWXPay({
						timestamp: item.timestamp, // 支付签名时间戳，注意微信 jssdk 中的所有使用 timestamp 字段均为小写。但最新版的支付后台生成签名使用的 timeStamp 字段名需大写其中的 S 字符
						nonceStr: item.nonceStr, // 支付签名随机串，不长于 32 位
						package: item.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
						signType: item.signType, // 微信支付V3的传入 RSA ,微信支付V2的传入格式与V2统一下单的签名格式保持一致
						paySign: item.paySign, // 支付签名
						success: r => {
							if (r.errMsg === 'chooseWXPay:ok') {
								this.detail.delivery_type = this.active
								sessionStorage.setItem('order', JSON.stringify(this.order_id))
								console.log(
									this.order_id,
									JSON.parse(sessionStorage.getItem('order'))
								)
								window.location.href = './orderCheck.html'
							}
						},
						cancel: r => {
							this.$toast.fail({
								message: '取消支付',
							})
							this.checkOrder()
						},
						fail: r => {
							this.$toast.fail({
								message: '支付失败!',
							})
							this.checkOrder()
						},
					})
				},
				checkOrder() {
					console.log(this.order_id)
					getAction(spliceUrl('/shop/order/status'), {
						order_id: this.order_id,
					}).then(res => {
						res = res.data
						if (res.success) {
							this.is_pay = res.data.is_pay
						} else {
							this.$toast.fail({
								message: res.message,
							})
						}
					})
				},
				onPay() {
					postAction(spliceUrl('/shop/order/pay'), {
						order_id: this.order_id,
						patient_id: this.pid,
					}).then(res => {
						res = res.data
						if (res.success) {
							this.wxPay(res.data)
						} else {
							this.$toast.fail({
								message: res.message,
							})
						}
					})
				},
			},
			components: {},
		}

		const app = Vue.createApp(PatientData)

		app.use(vant)

		// 通过 CDN 引入时不会自动注册 Lazyload 组件
		// 可以通过下面的方式手动注册
		app.use(vant.Lazyload)

		// 调用函数组件，弹出一个 Toast
		// vant.Toast("刷新成功");

		app.mount('#app')
	</script>
</html>
